<?php
namespace app\home\controller;

use think\Cache;
use think\Controller;
use think\Cookie;
use think\Exception;
use think\Log;
use think\Session;
use think\config;
use app\home\validate;

class Login extends Controller
{
    /**
     *用户登录
     * @author wcy
     * @version 2017年7月17日09:54:44
     */
    public function login()
    {
        if($this->request->isGet()){
            $this->wblogin();
            return view("login");
        }else{
            $user_name=input("post.user_name");
            $pass_word=md5(input("post.pass_word"));
            $check=input("post.check");
            $res=model("BlogUser")->login($user_name,$pass_word);
            if($res){
                if($check=="None"){
                    //用户记住一周
                    Cookie::set("cookieuser",$res,60*60*24*7);
                }
                Session::set("bloguser",$res);
                return json(["code"=>1,"msg"=>"登录成功！"]);
            }else{
                return json(["code"=>-1,"msg"=>"账号或密码错误！"]);
            }
        }

    }
    /**
     * QQ登录
     * @author wcy
     * @version 2017年8月14日10:35:05
     */
    public function qqLogin(){
        try{
            require_once("../thinkphp/library/think/sdklogin/qqSDK.class.php");
            $qc = new \qqSDK();
            $url=$qc->qq_login();
            $this->redirect($url);
        }catch (Exception $e){
            Log::record($e->getMessage());
            return false;
        }
    }
    //qq回调地址
    public function qqLoginCallBack(){
        require_once("../thinkphp/library/think/sdklogin/qqSDK.class.php");
        //获取code
        $code=input("get.code");
        $state=input("get.state");
        $qc = new \qqSDK();
        //获取access_token
        $access_token=$qc->qq_token($code);
        //获取openid
        $openid=$qc->qq_openid($access_token);
        //判断用户是否已经登录过
        $data=model("BlogUser")->qqOpenid($openid);
        if(empty($data)){
            //添加QQ登录的用户信息
            $user_info=$qc->get_user_info($access_token,$openid);
            $data["openid"]=$openid;
            $data["nick_name"]=$user_info->nickname;
            $data["user_img"]=$user_info->figureurl_qq_1;
            $res=model("BlogUser")->addBlogUser($data);
            if($res!==false){
                $data=model("BlogUser")->qqOpenid($openid);
                Session::set("bloguser",$data);
                $this->redirect("Article/index");
            }
        }else{
            Session::set("bloguser",$data);
            $this->redirect("Article/index");
        }
    }
    /**
     *微博登录
     * @author wcy
     * @version 2017年8月21日15:29:50
     */
    public function wblogin(){
        require_once("../thinkphp/library/think/sdklogin/wbSDK.class.php");
        $o = new \wbSDK(config::get("sdk_config.wb_login")["WB_AKEY"] , config::get("sdk_config.wb_login")["WB_SKEY"] );
        $code_url = $o->getAuthorizeURL( config::get("sdk_config.wb_login")["WB_CALLBACK_URL"] );
        $this->assign("code_url",$code_url);
    }
    /**
     * 获取token
     * @author wcy
     * @version 2017年8月21日15:29:50
     */
    public function wblogincallback(){
        require_once("../thinkphp/library/think/sdklogin/wbSDK.class.php");
        $o = new \wbSDK(config::get("sdk_config.wb_login")["WB_AKEY"] , config::get("sdk_config.wb_login")["WB_SKEY"] );
        if (isset($_REQUEST['code'])) {
            $keys = array();
            $keys['code'] = $_REQUEST['code'];
            $keys['redirect_uri'] = config::get("sdk_config.wb_login")["WB_CALLBACK_URL"];
            try {
                $token = $o->getAccessToken( 'code', $keys ) ;
            } catch (OAuthException $e) {
            }
        }
        if ($token) {
            $this->wb_get_user_info($token["access_token"]);
        }
    }
    /**
     *获取微博用户的基本信息
     * @author wcy
     * @version 2017年8月21日16:34:20
     */
    public function wb_get_user_info($token){
        require_once("../thinkphp/library/think/sdklogin/wbSDK.class.php");
        $o = new \SaeTClientV2(config::get("sdk_config.wb_login")["WB_AKEY"] , config::get("sdk_config.wb_login")["WB_SKEY"]  , $token );
        $uid_get = $o->get_uid();
        $uid = $uid_get['uid'];
        $user_message = $o->show_user_by_id( $uid);//根据ID获取用户等基本信息
        $data=model("BlogUser")->wbOpenid($user_message["id"]);
        if(empty($data)){
            //添加QQ登录的用户信息
            $data["wb_openid"]=$user_message["id"];
            $data["nick_name"]=$user_message["screen_name"];
            $data["user_img"]=$user_message["profile_image_url"];
            $res=model("BlogUser")->addBlogUser($data);
            if($res!==false){
                $data=model("BlogUser")->wbOpenid($user_message["id"]);
                Session::set("bloguser",$data);
                $this->redirect("Article/index");
            }
        }else{
            Session::set("bloguser",$data);
            $this->redirect("Article/index");
        }
    }
    /**
     *用户注册
     * @author wcy
     * @version 2017年7月17日11:03:41
     */
    public function register(){
        if($this->request->isGet()){
            return view("register");
        }else{
            $data["user_name"]=input("post.user_name");
            $data["nick_name"]=input("post.nick_name");
            $data["pass_word"]=input("post.pass_word1");
            $data["phone"]=input("post.phone");
            $data["code"]=input("post.code");
            $validate=new validate\User();
            if($validate->check($data)){
                $pass_word1=input("post.pass_word1");
                $pass_word2=input("post.pass_word2");
//                $code=input("post.code");
//                if(Cache::get("code")==$code){
                    if($pass_word1!=$pass_word2){
                        return json(["code"=>-1,"msg"=>"密码不相同，请重新设置"]);
                    }
                    $data["user_name"]=input("post.user_name");
                    $blogUserData=model("BlogUser")->verifyUserName($data["user_name"]);
                    if($blogUserData){
                        return json(["code"=>-1,"msg"=>"账号名已经存在，请重新输入"]);
                    }
                    $data["pass_word"]=md5(input("post.pass_word1"));
                    $res=model("BlogUser")->addBlogUser($data);
                    if($res!==false){
                        return json(["code"=>1,"msg"=>"注册成功"]);
                    }else{
                        return json(["code"=>-1,"msg"=>"注册失败"]);
                    }
//                }else{
//                        return json(["code"=>-1,"msg"=>"验证码错误"]);
//                }
            }else{
                return json(["code"=>-1,"msg"=>$validate->getError()]);
            }
        }
    }
    /**
     *发送短信验证码
     * @author wcy
     * @version 2017年7月17日15:34:04
     */
    public function  note(){
        $phone=input("post.phone");
        if(empty($phone)){
            return json(["code"=>-1,"msg"=>"请输入电话号码"]);
        }
        $ACCOUNT_SID = "cb74361ad70d4997bb642045ac42d706"; // 主账户
        $AUTH_TOKEN = "d5a09d3088484f6c837977407ee6fd22";
        $code=rand(10000,99999);
        Cache::set("code",$code,300);
        $timestamp = date("YmdHis");
        $sig = md5($ACCOUNT_SID . $AUTH_TOKEN . $timestamp);
        $body= array("accountSid" => $ACCOUNT_SID, "timestamp" => $timestamp, "sig" => $sig, "respDataType"=> "JSON");
        $body['smsContent'] = "【猿科技】您的验证码为".$code."，请于5分钟内正确输入，如非本人操作，请忽略此短信。";
        $body['to'] = $phone;
        // 构造请求数据
        $headers =  array('Content-type: application/x-www-form-urlencoded'  , 'Accept: application/json' );;
        // 要求post请求的消息体为&拼接的字符串，所以做下面转换
        $fields_string = "";
        foreach ($body as $key => $value) {
            $fields_string .= $key . '=' . $value . '&';
        }
        rtrim($fields_string, '&');
        // 提交请求
        $con = curl_init();
        curl_setopt($con, CURLOPT_URL, "https://api.miaodiyun.com/20150822/industrySMS/sendSMS");
        curl_setopt($con, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($con, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($con, CURLOPT_HEADER, 0);
        curl_setopt($con, CURLOPT_POST, 1);
        curl_setopt($con, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($con, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($con, CURLOPT_POSTFIELDS, $fields_string);
        $result = curl_exec($con);
        curl_close($con);
        $json_data=json_decode($result,true);
        if($json_data["respCode"]=="00000"){
            return json(["code"=>1,"msg"=>"发送短信成功,请注意查收"]);
        }else{
            return json(["code"=>-1,"msg"=>"发送短信失败"]);
        }
    }
    /**
     *判断用户是否登录
     * @author wcy
     * @version 2017年9月11日14:00:09
     */
    public function isLogin(){
        try{
            $bloguser=Session::get("bloguser");
            if(!empty($bloguser)){
                return json(["code"=>1,"msg"=>"用户已登录"]);
            }else{
                return json(["code"=>-1,"msg"=>"用户未登录"]);
            }
        }catch (Exception $e){
            Log::record($e->getMessage());
            return json(["code"=>-1,"msg"=>"用户未登录"]);
        }
    }
    /**
     *退出
     * @author wcy
     * @version 2017年7月18日15:46:07
     */
    public function loginOut(){
        Session::clear();
        echo "<script>location.href='".$_SERVER["HTTP_REFERER"]."';</script>";
    }
}
